﻿using Core.Enums;
using Core.Event;
using Core.Librarys;
using Core.Models;
using Core.Models.Config;
using Core.Models.Config.Link;
using Core.Servicers.Interfaces;
using FileSC.Configs;
using FileSC.Configs.StatusBar;
using FileSC.Hangfire;
using FileSC.WEBService;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Threading;
using UI.Servicers;

namespace Core.Servicers.Instances
{
    public class Main : IMain
    {
        private readonly ISleepdiscover sleepdiscover;
        private readonly IAppConfig2 appConfig;
        private readonly IFileSCHttpServer _httpServer;
        private IStatusBarIconServicer bar;
        private readonly IHangfireService _hangfire;
        /// <summary>
        /// 睡眠状态
        /// </summary>
        private SleepStatus sleepStatus;

        public event EventHandler OnStarted;

        //  更新应用日期
        private DateTime updadteAppDateTime_ = DateTime.Now.Date;
        public Main(
            ISleepdiscover sleepdiscover,
            IAppConfig2 appConfig,
            IDateTimeObserver dateTimeObserver,
            IFileSCHttpServer httpServer,
            IHangfireService hangfire)
        {
            this.sleepdiscover = sleepdiscover;
            this.appConfig = appConfig;
            _httpServer = httpServer;
            _hangfire = hangfire;

            sleepdiscover.SleepStatusChanged += Sleepdiscover_SleepStatusChanged;
            this.appConfig.ConfigChanged += AppConfig_ConfigChanged;
        }

        public void LinkBar(IStatusBarIconServicer bar)
        {
            this.bar = bar;
        }
        private void AppConfig_ConfigChanged(ConfigModel oldConfig, ConfigModel newConfig)
        {
            if (oldConfig != newConfig)
            {
                //  处理开机自启
                SystemCommon.SetStartup(newConfig.General.IsStartatboot);
            }
        }

        public async void Run()
        {
            await Task.Run(() =>
             {
                 CreateDirectory();

                 ////  数据库自检
                 //using (var db = new TaiDbContext())
                 //{
                 //    db.SelfCheck();
                 //}


                 AppState.IsLoading = false;
             });
            appConfig.Load();
            _hangfire.Init();
            //  启动主服务
            Start();

            OnStarted?.Invoke(this, EventArgs.Empty);
        }
        public void Start()
        {
            //  appTimer必须比Observer先启动*
            _httpServer.Start();
            if (AppConfig.YesOrNo("睡眠监测"))
            {
                //  启动睡眠监测
                sleepdiscover.Start();
            }
            StatusBar.SetIcon(IconType.T1);
        }

        public void Stop()
        {
            _httpServer.Stop();
        }
        public void Exit()
        {
            _httpServer.Stop();
        }

        /// <summary>
        /// 创建程序目录
        /// </summary>
        private void CreateDirectory()
        {
            string dir = Path.Combine(FileHelper.GetRootDirectory(), "Data");
            Directory.CreateDirectory(dir);
        }
        private bool IsRegex(string str)
        {
            return Regex.IsMatch(str, @"[\.|\*|\?|\{|\\|\[|\^|\|]");
        }

        private void Sleepdiscover_SleepStatusChanged(Enums.SleepStatus sleepStatus)
        {
            this.sleepStatus = sleepStatus;

            Logger.Info($"[{sleepStatus}]");
            if (sleepStatus == SleepStatus.Sleep)
            {
                //  进入睡眠状态
                Debug.WriteLine("进入睡眠状态");

                //  停止服务
                Stop();
            }
            else
            {
                //  从睡眠状态唤醒
                Debug.WriteLine("从睡眠状态唤醒");

                Start();
            }
        }
    }
}
